// import * as mars3d from "mars3d"

/* initMap() {
  // 创建三维地球场景
  const map = new mars3d.Map("mars3dContainer", {
    scene: {
      center: { lat: 30.52, lng: 114.31, alt: 17036414, heading: 0, pitch: -45 },
      showSun: true,
      showMoon: true,
      showSkyBox: true,
      showSkyAtmosphere: false, // 关闭球周边的白色轮廓 map.scene.skyAtmosphere = false
      fog: true,
      fxaa: true,
      globe: {
        showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
        depthTestAgainstTerrain: false,
        baseColor: "#546a53"
      },
      cameraController: {
        zoomFactor: 3.0,
        minimumZoomDistance: 1,
        maximumZoomDistance: 50000000,
        enableRotate: true,
        enableZoom: true
      },
      mapProjection: mars3d.CRS.EPSG3857, // 2D下展示墨卡托投影
      mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL// 2D下左右一直可以滚动重复世界地图
    },
    control: {
      baseLayerPicker: true, // basemaps底图切换按钮
      homeButton: true, // 视角复位按钮
      sceneModePicker: true, // 二三维切换按钮
      navigationHelpButton: true, // 帮助按钮
      fullscreenButton: true, // 全屏按钮
      contextmenu: { hasDefault: true } // 右键菜单
    },
    terrain: {
      url: "http://data.mars3d.cn/terrain",
      show: true
    },
    basemaps: [
      {
        name: "天地图影像",
        icon: "img/basemaps/tdt_img.png",
        type: "tdt",
        layer: "img_d",
        show: true
      }
    ]
  })

  return map
}
*/

var map // mars3d.Map三维地图对象
var graphicLayer // 矢量图层对象
var eventTarget = new mars3d.BaseClass()

// 需要覆盖config.json中地图属性参数（当前示例框架中自动处理合并）
var mapOptions = {
  scene: {
    center: { lat: -60.772952, lng: -60.609338, alt: 5604251, heading: 0, pitch: -90 }

  },
  control: {
    geocoder: false
  }
}

//  // 需要覆盖config.json中地图属性参数（当前示例框架中自动处理合并）
//  var mapOptions = function (option) {
//   option.control = {
//     // geocoder: true 
//     geocoder: "gaode" 
//   }
//   return option
// }

/**
 * 初始化地图业务，生命周期钩子函数（必须）
 * 框架在地图初始化完成后自动调用该函数
 * @param {mars3d.Map} mapInstance 地图对象
 * @returns {void} 无
 */
function onMounted(mapInstance) {
  map = mapInstance // 记录map
map.on(mars3d.EventType.load, function (event) {
  var destination = new mars3d.LngLatPoint( 114.209338,30.772952, 25604251);
  var destination1 = new mars3d.LngLatPoint( 114.209338,30.772952, 9604251);
  var options = {
    radius: 1000, // 相机距离目标点的距离（单位：米）
    duration: 2, // 飞行持续时间（单位：秒）
    heading: 0 // 相机的方向角（0至360度之间
  };
  map.flyToPoint(destination, options); // 设置飞行参数并触发第一个飞行效果

  setTimeout(function() {
    map.flyToPoint(destination1, options); // 设置飞行参数并触发第二个飞行效果
  }, 2024); // 设置延迟时间为100毫秒
  
        })
  var poiQueryButton = new PoiQueryButton({
    insertIndex: 0 // 插入的位置顺序
  })
  map.addControl(poiQueryButton)
  // // 查询结果回调方法
  // map.controls.geocoder._czmContrl.viewModel.complete.addEventListener(function () {
  //   var arrdata = map.controls.geocoder._czmContrl.viewModel.suggestions
  //   console.log("查询结果", arrdata)
  // })

  // 创建矢量数据图层
  graphicLayer = new mars3d.layer.GraphicLayer()
  map.addLayer(graphicLayer)

  // 在layer上绑定监听事件
  graphicLayer.on(mars3d.EventType.click, function (event) {
    console.log("监听layer，单击了矢量对象", event)
    
    if(flag==1){
      bindLayerPopup1() 
    }
    else if(flag==2){
      bindLayerPopup2()
    }
    else if(flag==3){
      bindLayerPopup3()
    }
    else if(flag==4){
      bindLayerPopup4()
    }
    else if(flag==5){
      bindLayerPopup5()
    }
    else {
      bindLayerPopup6()
    }
  })

  //bindLayerPopup() // 在图层上绑定popup,对所有加到这个图层的矢量数据都生效





  bindLayerContextMenu() // 在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效

  // 加一些演示数据
  // addDemoGraphic1(graphicLayer)
  // addDemoGraphic2(graphicLayer)
}

/**
 * 释放当前地图业务的生命周期函数
 * @returns {void} 无
 */
function onUnmounted() {
  map = null
  graphicLayer.remove()
  graphicLayer = null
}


// 也可以在单个Graphic上做个性化管理及绑定操作
function initGraphicManager(graphic) {
  // 3.在graphic上绑定监听事件
  // graphic.on(mars3d.EventType.click, function (event) {
  //   console.log("监听graphic，单击了矢量对象", event)
  // })
  // 绑定Tooltip
  // graphic.bindTooltip('我是graphic上绑定的Tooltip') //.openTooltip()

  // 绑定Popup
  const inthtml = `<table style="width: auto;">
            <tr>
              <th scope="col" colspan="2" style="text-align:center;font-size:15px;">我是graphic上绑定的Popup </th>
            </tr>
            <tr>
              <td>提示：</td>
              <td>这只是测试信息，可以任意html</td>
            </tr>
          </table>`
  graphic.bindPopup(inthtml).openPopup()

  // 绑定右键菜单
  graphic.bindContextMenu([
    {
      text: "删除对象[graphic绑定的]",
      icon: "fa fa-trash-o",
      callback: (e) => {
        const graphic = e.graphic
        if (graphic) {
          graphic.remove()
        }
      }
    }
  ])

  // 测试 颜色闪烁
  if (graphic.startFlicker) {
    graphic.startFlicker({
      time: 20, // 闪烁时长（秒）
      maxAlpha: 0.5,
      color: Cesium.Color.YELLOW,
      onEnd: function () {
        // 结束后回调
      }
    })
  }
}

// 有衬色边线,附带的label演示，导出geojson，加载geojson
// function addDemoGraphic1(graphicLayer) {
//   const graphic = new mars3d.graphic.PolylineEntity({
//     positions: [
//       [114.372852, 30.502736, 33.69],
//       [114.351461, 30.516011, 26.44]
//     ],
//     style: {
//       width: 6,
//       materialType: mars3d.MaterialType.PolylineOutline,
//       materialOptions: {
//         color: Cesium.Color.ORANGE,
//         outlineWidth: 2,
//         outlineColor: Cesium.Color.BLACK
//       },
//       label: {
//         text: "我是原始线",
//         font_size: 18,
//         color: "#ffffff",
//         distanceDisplayCondition: true,
//         distanceDisplayCondition_far: 500000,
//         distanceDisplayCondition_near: 0
//       }
//     },
//     attr: { remark: "示例1" }
//   })
//   graphicLayer.addGraphic(graphic)

//   // graphic转geojson
//   const geojson = graphic.toGeoJSON()
//   console.log("转换后的geojson", geojson)
//   addGeoJson(geojson, graphicLayer)
// }

// // 添加单个geojson为graphic，多个直接用graphicLayer.loadGeoJSON
// function addGeoJson(geojson, graphicLayer) {
//   const graphicCopy = mars3d.Util.geoJsonToGraphics(geojson)[0]
//   delete graphicCopy.attr
//   // 新的坐标
//   graphicCopy.positions = [
//     [114.372852, 30.512736, 33.69],
//     [114.351461, 30.526011, 26.44]
//   ]
//   graphicCopy.style.label = graphicCopy.style.label || {}
//   graphicCopy.style.label.text = "我是转换后生成的"
//   graphicLayer.addGraphic(graphicCopy)
// }

// // 箭头线
// function addDemoGraphic2(graphicLayer) {
//   const graphic = new mars3d.graphic.PolylineEntity({
//     positions: [
//       [114.34577, 30.52355, 12.23],
//       [114.38784, 30.62045, 11.78]
//     ],
//     style: {
//       width: 8,
//       clampToGround: true,
//       materialType: mars3d.MaterialType.PolylineArrow,
//       materialOptions: {
//         color: Cesium.Color.YELLOW
//       }
//     },
//     attr: { remark: "示例2" }
//   })
//   graphicLayer.addGraphic(graphic)
// }


// 生成演示数据(测试数据量)
function addRandomGraphicByCount(count) {
  graphicLayer.clear()
  graphicLayer.enabledEvent = false // 关闭事件，大数据addGraphic时影响加载时间

  const bbox = [116.984788, 31.625909, 117.484068, 32.021504]
  const result = mars3d.PolyUtil.getGridPoints(bbox, count, 30)
  console.log("生成的测试网格坐标", result)

  for (let j = 0; j < result.points.length; ++j) {
    const position = result.points[j]
    const index = j + 1

    const pt1 = mars3d.PointUtil.getPositionByDirectionAndLen(position, 225, result.radius)
    const pt2 = mars3d.PointUtil.getPositionByDirectionAndLen(position, 315, result.radius)

    const graphic = new mars3d.graphic.PolylineEntity({
      positions: [pt1, position, pt2],
      style: {
        width: 3.0,
        color: Cesium.Color.fromRandom({ alpha: 1.0 })
      },
      attr: { index }
    })
    graphicLayer.addGraphic(graphic)
  }

  graphicLayer.enabledEvent = true // 恢复事件
  return result.points.length
}

// 开始绘制
function startDrawGraphic() {
  graphicLayer.startDraw({
    type: "polyline",
    // maxPointNum: 2, //可以限定最大点数，2个点绘制后自动结束
    style: {
      color: "#55ff33",
      width: 3,
      clampToGround: false,
      label: {
        font_size: 18,
        color: "#ffffff",
        distanceDisplayCondition: true,
        distanceDisplayCondition_far: 500000,
        distanceDisplayCondition_near: 0
      }
    }
  })
}

// 开始绘制
function startDrawGraphic2() {
  graphicLayer.startDraw({
    type: "polyline",
    style: {
      color: "#ff0000",
      width: 3,
      closure: true
    }
  })
}

// 开始绘制 自由曲线
function startDrawBrushLine() {
  graphicLayer.startDraw({
    type: "brushLine",
    style: {
      color: "#55ff33",
      width: 3,
      clampToGround: false
    }
  })
}



// 在图层绑定Popup弹窗
function bindLayerPopup1() {
  graphicLayer.bindPopup(function (event) {
    const attr = event.graphic.attr || {}
    attr["类型"] = event.graphic.type
    // attr["来源"] = "我是layer上绑定的Popup"
    // attr["备注"] = "我支持鼠标交互"
    const name =event.graphic.attr.Reporter_data1;
    const TradeValue =event.graphic.attr.TradeValue_1000;
    const intro = event.graphic.attr.introduction;
    const caplng = event.graphic.attr.caplng;
    const caplat = event.graphic.attr.caplat;
    const area = event.graphic.attr.Shape_Area;
    const iso = event.graphic.attr.code;

    var attr1 = {};
  
       attr1["国家名字："]=name
       attr1["国家简称："]=iso
       attr1['首都坐标：']="( "+caplng+" , "+caplat+" )"
       attr1["贸易总额："]=TradeValue*1000+ " $"
       attr1['国家简介：']=intro
       attr1['国土面积：']=area+"   km²"
       

    return mars3d.Util.getTemplateHtml({ title: "总额可视化", template: "all",  attr: attr1 })
  })
}

//线数据可视化
function bindLayerPopup2() {
  graphicLayer.bindPopup(function (event) {
    const attr = event.graphic.attr || {}
    attr["类型"] = event.graphic.type
    // attr["来源"] = "我是layer上绑定的Popup"
    // attr["备注"] = "我支持鼠标交互"
    const start =event.graphic.attr.start_country;
    const value =event.graphic.attr.TradeValue;
    const end = event.graphic.attr.end_country;

    var attr2 = {};
  
       attr2["出口国家："]=start
       attr2["进口国家："]=end
       attr2['贸易额：']=value+" $"
       
    return mars3d.Util.getTemplateHtml({ title: "贸易流线可视化", template: "all",  attr: attr2 })
  })
}

//社团划分可视化
function bindLayerPopup3() {
  graphicLayer.bindPopup(function (event) {
    const attr = event.graphic.attr || {}
    attr["类型"] = event.graphic.type
    // attr["来源"] = "我是layer上绑定的Popup"
    // attr["备注"] = "我支持鼠标交互"
    const name =event.graphic.attr.Country;
    const TradeValue =event.graphic.attr.TradeValue_1000;
    const Typeshequ =event.graphic.attr.Type;
    const intro = event.graphic.attr.introduction;
    const caplng = event.graphic.attr.caplng;
    const caplat = event.graphic.attr.caplat;
    const area = event.graphic.attr.Shape_Area;
    const iso = event.graphic.attr.code;

    var attr3 = {};
  
       attr3["国家名字："]=name
       attr3["国家简称："]=iso
       attr3['首都坐标：']="( "+caplng+" , "+caplat+" )"
       attr3["贸易总额："]=TradeValue*1000+ " $"
       attr3["社区类型："]="社区 "+Typeshequ
       attr3['国家简介：']=intro
       attr3['国土面积：']=area+"   km²"
       

    return mars3d.Util.getTemplateHtml({ title: "贸易社团划分", template: "all",  attr: attr3 })
  })
}

//出口重要国家可视化
function bindLayerPopup4() {
  graphicLayer.bindPopup(function (event) {
    const attr = event.graphic.attr || {}
    attr["类型"] = event.graphic.type
    // attr["来源"] = "我是layer上绑定的Popup"
    // attr["备注"] = "我支持鼠标交互"
    const name =event.graphic.attr.Country;
    const Value =event.graphic.attr.ExportValue_1000;
    const intro = event.graphic.attr.introduction;
    const caplng = event.graphic.attr.caplng;
    const caplat = event.graphic.attr.caplat;
    const area = event.graphic.attr.Shape_Area;
    const iso = event.graphic.attr.code;
    const ranking = event.graphic.attr.Rank;

    var attr4 = {};
  
       attr4["国家名字："]=name
       attr4["国家简称："]=iso
       attr4['首都坐标：']="( "+caplng+" , "+caplat+" )"
       attr4["贸易总额："]=Value*1000+ " $"
       attr4['排名']="第 "+ranking
       attr4['国家简介：']=intro
       attr4['国土面积：']=area+"   km²"
       

    return mars3d.Util.getTemplateHtml({ title: "出口重要国家", template: "all",  attr: attr4 })
  })
}

//进口重要国家可视化
function bindLayerPopup5() {
  graphicLayer.bindPopup(function (event) {
    const attr = event.graphic.attr || {}
    attr["类型"] = event.graphic.type
    // attr["来源"] = "我是layer上绑定的Popup"
    // attr["备注"] = "我支持鼠标交互"
    const name =event.graphic.attr.Country;
    const Value =event.graphic.attr.ImportValue_1000;
    const intro = event.graphic.attr.introduction;
    const caplng = event.graphic.attr.caplng;
    const caplat = event.graphic.attr.caplat;
    const area = event.graphic.attr.Shape_Area;
    const iso = event.graphic.attr.code;
    const ranking = event.graphic.attr.Rank;

    var attr5 = {};
  
       attr5["国家名字："]=name
       attr5["国家简称："]=iso
       attr5['首都坐标：']="( "+caplng+" , "+caplat+" )"
       attr5["贸易总额："]=Value*1000+ " $"
       attr5['排名']="第 "+ranking
       attr5['国家简介：']=intro
       attr5['国土面积：']=area+"   km²"
       

    return mars3d.Util.getTemplateHtml({ title: "进口重要国家", template: "all",  attr: attr5 })
  })
}

//拉普拉斯中心性重要国家可视化
function bindLayerPopup6() {
  graphicLayer.bindPopup(function (event) {
    const attr = event.graphic.attr || {}
    attr["类型"] = event.graphic.type
    // attr["来源"] = "我是layer上绑定的Popup"
    // attr["备注"] = "我支持鼠标交互"
    const name =event.graphic.attr.Country;
    const Value =event.graphic.attr.TradeValue_1000;
    const intro = event.graphic.attr.introduction;
    const caplng = event.graphic.attr.caplng;
    const caplat = event.graphic.attr.caplat;
    const area = event.graphic.attr.Shape_Area;
    const iso = event.graphic.attr.code;
    const ranking = event.graphic.attr.Rank;

    var attr6 = {};
  
       attr6["国家名字："]=name
       attr6["国家简称："]=iso
       attr6['首都坐标：']="( "+caplng+" , "+caplat+" )"
       attr6["贸易总额："]=Value*1000+ " $"
       attr6['排名']="第 "+ranking
       attr6['国家简介：']=intro
       attr6['国土面积：']=area+"   km²"
       

    return mars3d.Util.getTemplateHtml({ title: "拉普拉斯中心性重要国家", template: "all",  attr: attr6 })
  })
}


// 绑定右键菜单
function bindLayerContextMenu() {
  graphicLayer.bindContextMenu([
    {
      text: "开始编辑对象",
      icon: "fa fa-edit",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic || !graphic.hasEdit) {
          return false
        }
        return !graphic.isEditing
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        if (graphic) {
          graphicLayer.startEditing(graphic)
        }
      }
    },
    {
      text: "停止编辑对象",
      icon: "fa fa-edit",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic || !graphic.hasEdit) {
          return false
        }
        return graphic.isEditing
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        if (graphic) {
          graphic.stopEditing()
        }
      }
    },
    {
      text: "删除对象",
      icon: "fa fa-trash-o",
      show: (event) => {
        const graphic = event.graphic
        if (!graphic || graphic.isDestroy) {
          return false
        } else {
          return true
        }
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return
        }
        const parent = graphic.parent // 右击是编辑点时
        graphicLayer.removeGraphic(graphic)
        if (parent) {
          graphicLayer.removeGraphic(parent)
        }
      }
    },
    {
      text: "计算长度",
      icon: "fa fa-medium",
      callback: (e) => {
        const graphic = e.graphic
        const strDis = mars3d.MeasureUtil.formatDistance(graphic.distance)
        globalAlert("该对象的长度为:" + strDis)
      }
    }
  ])
}
